package classes;

import java.net.URL;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import containers.Page;
import containers.StartContainer;
import containers.StatisticsContainer;

public class Test {
	public static final int PROCESS_LIMIT_1 = 1;
	public static final int PROCESS_LIMIT = 14;
	//TODO - change process_limit_10 to be 10 and create a new PRocess_limit_14.
	
	public static void main(final String[] args) {
		//initialize collections.
		final BlockingQueue<StartContainer> startQ = new ArrayBlockingQueue<StartContainer>(PROCESS_LIMIT_1);
		final BlockingQueue<Page> pageQ = new ArrayBlockingQueue<Page>(PROCESS_LIMIT*10); /**Queue for Pages going from PR to PP*/
		final BlockingQueue<List<URL>> urlQ = new ArrayBlockingQueue<List<URL>>(PROCESS_LIMIT*10); /**Queue for URLs going from PP to PR.*/
		final BlockingQueue<Page> analQ = new ArrayBlockingQueue<Page>(PROCESS_LIMIT*10);/**Queue for Pages going from PP to PA.*/
		final BlockingQueue<StatisticsContainer> statQ = new ArrayBlockingQueue<StatisticsContainer>(PROCESS_LIMIT_1);
		final BlockingQueue<List<String>> keywordQ = new ArrayBlockingQueue<List<String>>(PROCESS_LIMIT_1);
		
		//initialize class objects.
		UserInterface myUI;
		PageRetriever myPR;
		PageParser myPP;
		PageAnalyzer myPA;
		

		//create threads
		Thread uiThread = new Thread(myUI = new UserInterface(startQ, statQ, keywordQ));
		Thread prThread = new Thread(myPR = new PageRetriever(startQ, urlQ, pageQ));
		Thread ppThread = new Thread(myPP = new PageParser(pageQ, urlQ, analQ));
		Thread paThread = new Thread(myPA = new PageAnalyzer(analQ, statQ, keywordQ));
				
		//startThreads
		uiThread.start();
		prThread.start();
		ppThread.start();
		paThread.start();
		

		
		while(!myUI.isStartDone()) {};
		 
		boolean running = true;
		
		while(running){
			pauseHalf();
			if(prThread.getState() == Thread.State.WAITING && ppThread.getState() == Thread.State.WAITING 
					&& paThread.getState() == Thread.State.WAITING && pageQ.isEmpty() && urlQ.isEmpty() 
					&& analQ.isEmpty() && startQ.isEmpty()) {
					myPR.stop();
					prThread.interrupt();
					
					myPP.stop();
					ppThread.interrupt();
					
					
					myPA.stop();
					paThread.interrupt();
					
					running = false;
				}
			
				if (!prThread.isAlive() && !ppThread.isAlive() && !paThread.isAlive()) {
					//program is already done;
					running = false;
				}
		}
	}
	
	public static void pauseHalf() {
		for (int i = 0; i < 2000000; i++);
	}
}
